"""
@author: j.l.liu
@create: 
@description: # 启动命令：uvicorn translate_api:app --reload --port 8000
中英文翻译，百度通用文本翻译，免费字符5万/月
启动后，postman掉接口，传递参数{"text": "你好", "direction": "zh2en"}接口
"""
import hashlib
import random

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import requests

app = FastAPI(title="双向翻译-百度版")

# 百度翻译公共实例，也可自建
BAIDU_URL = "https://fanyi-api.baidu.com/api/trans/vip/translate"
APP_ID = '20250717002408958'
SECRET_KEY = '7PS10fWs6snBdILjpc2L'


class Item(BaseModel):
    text: str
    direction: str  # "zh2en" or "en2zh"


@app.post("/translate")
def translate(item: Item):
    if not item.text.strip():
        raise HTTPException(status_code=400, detail="text 不能为空")

    src, dst = ("zh", "en") if item.direction == "zh2en" else ("en", "zh")
    salt = str(random.randint(10000, 99999))
    sign = hashlib.md5((APP_ID + item.text + salt + SECRET_KEY).encode()).hexdigest()

    payload = {
        "q": item.text,
        "from": src,
        "to": dst,
        "appid": APP_ID,
        "salt": salt,
        "sign": sign
    }

    r = requests.post(BAIDU_URL, data=payload, timeout=5)
    data = r.json()
    if "trans_result" not in data:
        raise HTTPException(status_code=500, detail=data.get("error_msg", "unknown"))

    return {"result": data["trans_result"][0]["dst"]}


